package cn.com.yusys.yusp.admin.web.rest;

import cn.com.yusys.yusp.admin.domain.AdminSmUser;
import cn.com.yusys.yusp.admin.domain.AdminSmUserDutyRel;
import cn.com.yusys.yusp.admin.domain.AdminSmUserMgrOrg;
import cn.com.yusys.yusp.admin.domain.AdminSmUserRoleRel;
import cn.com.yusys.yusp.admin.service.AdminSmUserService;
import cn.com.yusys.yusp.commons.mapper.QueryModel;
import cn.com.yusys.yusp.commons.service.CommonService;
import cn.com.yusys.yusp.commons.util.DateUtil;
import cn.com.yusys.yusp.commons.web.rest.CommonResource;
import cn.com.yusys.yusp.commons.web.rest.dto.ResultDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0.0
 * @项目名称: yusp-admin
 * @类名称: AdminSmUserResource
 * @类描述: 用户管理Resource
 * @功能描述:
 * @创建人: hujun@yusys.com.cn
 * @创建时间: 2017-12-25 10:38
 * @修改备注:
 * @修改记录: 修改时间    修改人员    修改原因
 * -------------------------------------------------------------
 * @Copyright (c) 2018宇信科技-版权所有
 */
@RestController
@RequestMapping("api/adminsmuser")
public class AdminSmUserResource extends CommonResource<AdminSmUser, String> {

    private Logger logger = LoggerFactory.getLogger(AdminSmUserResource.class);

    @Autowired
    private AdminSmUserService service;

    @Override
    protected CommonService getCommonService() {
        return this.service;
    }

    /**
     * @方法名称: getList
     * @方法描述: 分页查询
     * @参数与返回说明:
     * @算法描述:
     */
    @GetMapping("/querypage")
    public ResultDto<List<Map<String, Object>>> getList(QueryModel queryModel) {
        List<Map<String, Object>> list = service.findAllByParam(queryModel);
        return new ResultDto<List<Map<String, Object>>>(list);
    }

    /**
     * @方法名称: getListByRolests
     * @方法描述: 查询角色数据，只可关联用户所在机构及上级机构的生效角色
     * @参数与返回说明:
     * @算法描述:
     */
    @GetMapping("/querybyrolests")
    public ResultDto<List<Map<String, Object>>> getListByRolests(@RequestParam String orgId) {
        List<Map<String, Object>> list = service.getListByRolests(orgId);
        return new ResultDto<List<Map<String, Object>>>(list.size(), list);
    }

    /**
     * @方法名称: getUserRole
     * @方法描述: 查询用户角色数据
     * @参数与返回说明:
     * @算法描述:
     */
    @GetMapping("/queryuserrole")
    public ResultDto<Object> getUserRole(QueryModel queryModel) {
        List<Map<String, Object>> list = service.findUserRole(queryModel);
        return new ResultDto<Object>(list.size(), list);
    }

    /**
     * @方法名称: getListByRolests
     * @方法描述: 查询岗位数据，只可关联用户所在机构及上级机构的生效岗位
     * @参数与返回说明:
     * @算法描述:
     */
    @GetMapping("/querybyduty")
    public ResultDto<List<Map<String, Object>>> getListByDuty(@RequestParam String orgId) {
        List<Map<String, Object>> list = service.getListByDuty(orgId);
        return new ResultDto<List<Map<String, Object>>>(list.size(), list);
    }

    /**
     * @方法名称: getUserDuty
     * @方法描述: 查询用户岗位
     * @参数与返回说明:
     * @算法描述:
     */
    @GetMapping("/queryuserduty")
    public ResultDto<Object> getUserDuty(QueryModel queryModel) {
        List<Map<String, Object>> list = service.findUserDuty(queryModel);
        return new ResultDto<Object>(list.size(), list);
    }

    /**
     * @方法名称: getUserOrg
     * @方法描述: 查询用户授权机构
     * @参数与返回说明:
     * @算法描述:
     */
    @GetMapping("/queryuserorg")
    public ResultDto<Object> getUserOrg(QueryModel queryModel) {
        List<Map<String, Object>> list = service.findUserOrg(queryModel);
        return new ResultDto<Object>(list.size(), list);
    }

    /**
     * @方法名称: addUserInfo
     * @方法描述: 新增用户数据
     * @参数与返回说明:
     * @算法描述:
     */
    @PostMapping("/adduserinfo")
    public ResultDto<Object> addUserInfo(@RequestBody AdminSmUser pool) throws Exception {
        Map<String, Object> list = service.insertInfo(pool);
        return new ResultDto<Object>(list);
    }

    @PostMapping("/updateUserPassword")
    public ResultDto<Object> updateUserPassword(@RequestBody Map map) throws Exception {
        int updateStatus = service.updateUserPassword(map);
        return new ResultDto<Object>(updateStatus);
    }

    /**
     * @方法名称: useBatch
     * @方法描述: 启用
     * @参数与返回说明: ids 数据ID主键
     * @算法描述:
     */
    @PostMapping("/usebatch")
    public ResultDto<Object> useBatch(@RequestParam("id") String ids, @RequestParam("userId") String userId) {
        int n = 0;
        ResultDto<Object> resultDto = new ResultDto<>();
        String id = "";
        if (ids != null && !"".equals(ids.toString())) {
            String[] idStr = ids.toString().split(",");
            for (int i = 0; i < idStr.length; i++) {
                if (!"".equals(idStr[i])) {
                    n = n + this.service.updateSts("A", idStr[i], userId);
                    id = id + ',' + idStr[i];
                }
            }
            String message = "用户批量启用  【主键：" + ids + "】 " + DateUtil.formatDateTimeByDef();
            resultDto.setMessage(message);
            logger.info(message);
        }
        resultDto.setData(n);
        return resultDto;
    }

    /**
     * @方法名称: unUseBatch
     * @方法描述: 停用
     * @参数与返回说明: ids 数据ID主键
     * @算法描述:
     */
    @PostMapping("/unusebatch")
    public ResultDto<Object> unUseBatch(@RequestParam("id") String ids, @RequestParam("userId") String userId) {
        int n = 0;
        ResultDto<Object> resultDto = new ResultDto<>();
        String id = "";
        if (ids != null && !"".equals(ids.toString())) {
            String[] idStr = ids.toString().split(",");
            for (int i = 0; i < idStr.length; i++) {
                if (!"".equals(idStr[i])) {
                    n = n + this.service.updateSts("I", idStr[i], userId);
                    id = id + ',' + idStr[i];
                }
            }
            String message = "用户批量停用  【主键：" + ids + "】 " + DateUtil.formatDateTimeByDef();
            resultDto.setMessage(message);
            logger.info(message);
        }

        resultDto.setData(n);
        return resultDto;
    }

    /**
     * @方法名称: deleteBatch
     * @方法描述: 删除
     * @参数与返回说明: ids 数据ID主键
     * @算法描述:
     */
    @PostMapping("/deletebatch")
    public ResultDto<Object> deleteBatch(@RequestParam("id") String ids) {
        int n = 0;
        ResultDto<Object> resultDto = new ResultDto<>();
        String id = "";
        if (ids != null && !"".equals(ids.toString())) {
            String[] idStr = ids.toString().split(",");
            for (int i = 0; i < idStr.length; i++) {
                if (!"".equals(idStr[i])) {
                    n = n + this.service.deleteByPrimaryKey(idStr[i]);
                    this.service.removeUserRaleInfo(idStr[i], "role");//删除角色关联数据
                    this.service.removeUserRaleInfo(idStr[i], "duty");//删除岗位关联数据
                    this.service.removeUserRaleInfo(idStr[i], "org");//删除授权机构数据
                    id = id + ',' + idStr[i];
                }
            }
            String message = "用户批量删除  【主键：" + ids + "】 " + DateUtil.formatDateTimeByDef();
            resultDto.setMessage(message);
            logger.info(message);
        }
        resultDto.setData(n);
        return resultDto;
    }

    /**
     * @方法名称: saveRole
     * @方法描述: 批量保存角色关联数据
     * @参数与返回说明:
     * @算法描述:
     */
    @PostMapping("/saverole/{paramId}")
    public ResultDto<Object> saveRole(@RequestBody ArrayList<AdminSmUserRoleRel> t, @PathVariable String paramId)
            throws Exception {
        int result = 0;
        List<AdminSmUserRoleRel> list = t;
        ResultDto<Object> resultDto = new ResultDto<>();
        try {
            //新增前先删除
            service.removeUserRaleInfo(paramId, "role");
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    AdminSmUserRoleRel pool = (AdminSmUserRoleRel) list.get(i);
                    result = result + service.addUserRole(pool);
                }
            }
            resultDto.setData(result);
            resultDto.setMessage("保存用户角色成功");
        } catch (Exception e) {
            resultDto.setCode(500);
            resultDto.setMessage(e.getMessage());
        }

        return resultDto;
    }

    /**
     * @方法名称: savePost
     * @方法描述: 批量保存岗位关联数据
     * @参数与返回说明:
     * @算法描述:
     */
    @PostMapping("/savepost/{paramId}")
    public ResultDto<Object> savePost(@RequestBody ArrayList<AdminSmUserDutyRel> t, @PathVariable String paramId)
            throws Exception {
        int result = 0;
        List<AdminSmUserDutyRel> list = t;
        ResultDto<Object> resultDto = new ResultDto<>();
        try {
            service.removeUserRaleInfo(paramId, "duty");
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    AdminSmUserDutyRel pool = (AdminSmUserDutyRel) list.get(i);
                    result = result + service.addUserDuty(pool);
                }
            }

            resultDto.setData(result);
            resultDto.setMessage("保存用户岗位成功");
        } catch (Exception e) {
            resultDto.setCode(500);
            resultDto.setMessage(e.getMessage());
        }
        return resultDto;
    }

    /**
     * @方法名称: saveOrg
     * @方法描述: 批量保存授权机构关联数据
     * @参数与返回说明:
     * @算法描述:
     */
    @PostMapping("/saveorg/{paramId}")
    public ResultDto<Object> saveOrg(@RequestBody ArrayList<AdminSmUserMgrOrg> t, @PathVariable String paramId)
            throws Exception {
        int result = 0;
        List<AdminSmUserMgrOrg> list = t;
        ResultDto<Object> resultDto = new ResultDto<>();
        try {
            service.removeUserRaleInfo(paramId, "org");
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    AdminSmUserMgrOrg pool = list.get(i);
                    result = result + service.addUserOrg(pool);
                }
            }

            resultDto.setData(result);
            resultDto.setMessage("保存用户机构成功");
        } catch (Exception e) {
            resultDto.setCode(500);
            resultDto.setMessage(e.getMessage());
        }
        return resultDto;
    }

    /**
     * @方法名称: resetPassword
     * @方法描述: 密码重置
     * @参数与返回说明:
     * @算法描述:
     */
    @PostMapping("/resetpwd")
    public ResultDto<Object> resetUserPassword(@RequestBody Map map) {
        String message = service.resetUserPassword(map);
        ResultDto<Object> resultDto = new ResultDto<>(message);
        if (message.equals("success")) {
            resultDto.setMessage("密码重置成功!");
        }
        return resultDto;
    }

    /**
     * 根据登录代码获取用户Id
     *
     * @param loginCode
     * @return
     */
    @PostMapping("/getUserId")
    public ResultDto<Object> getUserIdByLoginCode(String loginCode) {
        String userId = service.getUserIdByLoginCode(loginCode);
        ResultDto<Object> result = new ResultDto<>(userId);
        return result;
    }
}
